<template>
  <div class="dashboard-container waybill-list customer-list-box" style="width: 100%">
    <div class="app-container">
      <el-button type="warning" @click="addSubmit" style="margin-bottom: 22px">新增模板</el-button>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="templateType" label="模板类型" min-width="160px">
          <template slot-scope="scope">
            {{ scope.row.templateType | templateType }}
          </template>
        </el-table-column>
        <el-table-column prop="transportType" label="运送类型" min-width="160px">
          <template slot-scope="scope">
            {{ scope.row.transportType | translateType }}
          </template>
        </el-table-column>
        <el-table-column prop="associatedCityList" label="关联城市" min-width="160px">
          <template slot-scope="scope">
            {{ scope.row.associatedCityList | associatedCityList }}
          </template>
        </el-table-column>
        <el-table-column prop="firstWeight" label="首重" min-width="160px">
        </el-table-column>
        <el-table-column prop="continuousWeight" label="续重" min-width="160px">
        </el-table-column>
        <el-table-column prop="lightThrowingCoefficient" label="轻抛系数" min-width="160px">
        </el-table-column>
        <!-- 按钮操作 -->
        <el-table-column align="center" label="操作" min-width="200px">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="Edit(scope.row)">
              编辑
            </el-link>
            <i class="line" style="color:#dcdfe6">&nbsp;&nbsp;|&nbsp;&nbsp;</i>
            <el-link type="danger" :underline="false" @click="Delete(scope.row.id)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加模板弹窗 -->
    <el-dialog :title="type === 'add' ? '新增模板' : '编辑模板'" :visible="dialogVisible" width="600px" @close="closeDialog">
      <!-- 默认插槽表单模板 -->
      <div class="form-container">
        <el-form :model="priceForm" ref="addForm" :rules="addFormRules">
          <el-form-item label="模板类型" prop="templateType">
            <el-select class="input_width" v-model="priceForm.templateType" placeholder="请选择模板类型">
              <el-option v-for="(item, index) in templateTypeList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运送类型" prop="transportType">
            <el-select class="input_width" v-model="priceForm.transportType" placeholder="请选择运送类型">
              <el-option v-for="(item, index) in transportTypeList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联城市" prop="associatedCityList">
            <span v-if="priceForm.templateType !== 3">全国</span>
            <el-checkbox-group v-else v-model="checkedCities">
              <el-checkbox v-for="city in cities" :label="city" :key="city">{{ city }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="首重价格" prop="firstWeight">
            <el-input class="input_width" v-model="priceForm.firstWeight" placeholder="请输入续重价格">
              <template slot="suffix">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="续重价格" prop="continuousWeight">
            <el-input class="input_width" v-model="priceForm.continuousWeight" placeholder="请输入续重价格">
              <template slot="suffix">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="轻抛系数" prop="lightThrowingCoefficient">
            <el-input class="input_width" v-model="priceForm.lightThrowingCoefficient" placeholder="请输入清抛系数">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="warning" @click="submit('addForm')">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  freightManageList,
  freightManageOperate,
  freightManageDelete
} from '@/api/transit'

export default {
  data() {
    return {
      checkedCities: [],
      cities: ['京津冀', '江浙沪', '川渝', '黑吉辽'],
      tableData: [],
      isShowAll: true,
      // 控制弹窗的打开关闭
      dialogVisible: false,
      // 表单对象
      priceForm: {
        // id: '',
        templateType: '',
        transportType: '',
        associatedCityList: [1],
        firstWeight: '',
        continuousWeight: '',
        lightThrowingCoefficient: ''
      },
      //规则对象
      addFormRules: {
        //非空校验
        templateType: [
          { required: true, message: '模板类型不能为空', trigger: 'blur' }
        ],
        transportType: [
          { required: true, message: '运送类型不能为空', trigger: 'blur' }
        ],
        associatedCityList: [
          { required: true, message: '关联城市不能为空', trigger: 'blur' }
        ],
        firstWeight: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
                if (!reg.test(Number(value))) {
                  callback(
                    new Error('只能输入数字类型，最多保留两位小数，请重新输入')
                  )
                } else {
                  callback()
                }
              } else {
                callback(new Error('首重价格不能为空'))
              }
            },
            trigger: 'blur'
          }
        ],
        continuousWeight: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
                if (!reg.test(value)) {
                  callback(
                    new Error('只能输入数字类型，最多保留两位小数，请重新输入')
                  )
                } else {
                  callback()
                }
              } else {
                callback(new Error('续重价格不能为空'))
              }
            },
            trigger: 'blur'
          }
        ],
        lightThrowingCoefficient: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value) {
                const reg = /^[1-9]+[0-9]*$/
                if (!reg.test(value)) {
                  callback(new Error('只能输入正整数，请重新输入'))
                } else {
                  callback()
                }
              } else {
                callback(new Error('轻抛系数不能为空'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      // 关联城市
      associatedCityList: [
        {
          value: 2,
          label: '京津冀'
        },
        {
          value: 3,
          label: '江浙沪'
        },
      
  {
          value: 4,
          label: '川渝'
        },
        {
          value: 5,
          label: '黑吉辽'
        }
      ],
      // 模板类型
      templateTypeList: [
        {
          value: 1,
          label: '同城寄'
        },
        {
          value: 2,
          label: '省内寄'
        },
        {
          value: 3,
          label: '经济区互寄'
        },
        {
          value: 4,
          label: '跨省'
        }
      ],
      // 运送类型
      transportTypeList: [
        {
          value: 1,
          label: '普快'
        },
        {
          value: 2,
          label: '其他'
        }
      ],
      type: '',
      id: "",
    }
  },

  created() {
    this.getList()
  },
  // 过滤器
  // 模版类型
  filters: {
    templateType(value) {
      if (value == 1) {
        return '同城寄'
      } else if (value == 2) {
        return '省内寄'
      } else if (value == 3) {
        return '经济区互寄'
      } else {
        return '跨省'
      }
    },
    // 运送类型
    translateType(value) {
      if (value == 1) {
        return '普快'
      } else {
        return '其他'
      }
    },
    associatedCityList(value) {
      // console.log({ value })
      let city = {
        1: '全国',
        2: '京津冀',
        3: '江浙沪',
        4: '川渝',
        5: '黑吉辽',
      };
      let arr = [];
      (value || []).forEach(item => {
        // console.log({item})
        if ( ['5', '4', '3', '2', '1'].includes(item)) {
          arr.push(city[item])
        } else {
          arr = ['数据异常']
        }
      })
      // console.log({ arr })
      let str = arr.join(',')
      // console.log({ str })
      return str
    }
  },
  methods: {
    // 编辑运费模板
    Edit(row) {
      this.id = row.id;
      this.checkedCities = row.associatedCityList.length ? row.associatedCityList : [];
      this.priceForm = { ...row };
      this.dialogVisible = true
      this.type = 'edit',
        console.log('编辑')
      const arr = row.associatedCityList.map(item => {
        return Number(item)
      })
    },
    // 删除运费模板
    Delete(id) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await freightManageDelete(id);
        if (res.code == '200') {
          this.$message.success('删除成功')
          this.getList()
        } else {
          this.$message.error('取消删除')
        }
      })
    },
    // 添加运费(弹框确定按钮)
    submit(addForm) {
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          const data = {
            templateType: this.priceForm.templateType,
            transportType: this.priceForm.transportType,
            associatedCityList: this.priceForm.templateType != 3 ? [4] : this.checkedCities,
            firstWeight: this.priceForm.firstWeight,
            continuousWeight: this.priceForm.continuousWeight,
            lightThrowingCoefficient: this.priceForm.lightThrowingCoefficient
          }
          if (this.type == 'edit') {
            data.id = this.id;
          }

          freightManageOperate(data).then(res => {
            if (res.code == '200') {
              this.dialogVisible = false;
              this.$message({
                message: '操作成功！',
                type: 'success'
              })
              this.getList()
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 添加运费弹框
    addSubmit() {
      this.dialogVisible = true
      this.priceForm = {
        templateType: '',
        transportType: '',
        associatedCityList: [1],
        firstWeight: '',
        continuousWeight: '',
        lightThrowingCoefficient: ''
      }
      this.type = 'add'
    },
    closeDialog() {
      this.dialogVisible = false
      // 重置表单
      this.$refs.addForm.resetFields()
    },
    //获取运费列表渲染
    async getList() {
      const res = await freightManageList(this.params)
      console.log(res)
      this.tableData = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__footer {
  display: flex;
  justify-content: center
}

.el-input {
  width: 80% !important;
}

.input_width {
  width: 80%;
}
</style>

<style lang="scss" scoped rel="stylesheet/scss">
.waybill-list {
  .el-dialog__wrapper {
    ::v-deep .el-dialog__body {
      padding-left: 60px;
    }
  }
}

::v-deep .el-input__suffix {
  right: 20px !important;
  color: #000 !important;
}
</style>
